<template>
	<view class="message-box">
		<!-- 自定义导航栏 -->
		<custom-navbar title="留言箱" :show-back="true" @back="handleBack" />

		<view class="content" :style="{ paddingTop: navBarHeight + 'px' }">
			<view class="form-container mt30">
				<!-- 留言表单 -->
				<view class="foembox">
					<up-form label-position="left" :model="formData" ref="formRef">
						<!-- 留言分类 -->
						<up-form-item label="留言分类" :borderBottom="true" labelWidth="180"
							@click="showCategoryPicker = true">
							<up-input v-model="formData.category" placeholder="请选择留言分类（选填）" border="none" disabled
								disabledColor="#ffffff" inputAlign="right">
							</up-input>
							<template #right>
								<up-icon name="arrow-right"></up-icon>
							</template>
						</up-form-item>

						<!-- 联系人 -->
						<up-form-item label="联系人" :borderBottom="true" labelWidth="180">
							<up-input v-model="formData.name" placeholder="请输入联系人（选填）" border="none" clearable
								inputAlign="right">
							</up-input>
						</up-form-item>

						<!-- 联系电话 -->
						<up-form-item label="联系电话" :borderBottom="true" labelWidth="180">
							<up-input v-model="formData.phone" placeholder="请输入联系电话（选填）" border="none" clearable
								inputAlign="right">
							</up-input>
						</up-form-item>
					</up-form>
				</view>

				<!-- 反馈内容 -->
				<view class="form-section">
					<view class="section-title">反馈内容</view>
					<up-textarea v-model="formData.content" :maxlength='2000' :custom-style="textareaStyle"
						placeholder="请输入您的反馈内容（选填）">
					</up-textarea>
				</view>

				<!-- 图片上传 -->
				<view class="form-section">
					<view class="section-title">附件 (仅支持上传图片，最多9张)</view>
					<custom-upload :fileList="fileList" @afterRead="handleUpload" @delete="handleDelete"
						:maxCount="9" />
				</view>

				<!-- 提交按钮 -->
				<view class="submit-btn" @click="handleSubmit">提交留言</view>
			</view>
		</view>

		<!-- 分类选择器 -->
		<up-picker :show="showCategoryPicker" :columns="categoryColumns" @confirm="handleCategoryConfirm"
			@cancel="showCategoryPicker = false" />
	</view>
</template>

<script setup>
	import {
		ref,
		computed,
		onMounted
	} from 'vue'
	import CustomNavbar from '@/components/custom-navbar.vue'
	import CustomUpload from '@/components/custom-upload.vue'
	import {
		mySaveFeedback,
		uploadImage
	} from '@/api/user'
	import {
		getClassification
	} from '@/api/login'
	// 系统信息
	const systemInfo = uni.getSystemInfoSync()
	const navBarHeight = computed(() => systemInfo.statusBarHeight + 44)

	// 表单数据
	const formData = ref({
		category: '',
		name: '',
		phone: '',
		content: ''
	})

	// 文件列表（最多9张）
	const fileList = ref([])
	const MAX_FILE_COUNT = 9 // 定义最大上传数量
	const validatePhone = (phone) => {
		if (phone && !/^1[3-9]\d{9}$/.test(phone)) {
			uni.showToast({
				title: '请输入正确的手机号码',
				icon: 'none'
			})
			return false
		}
		return true
	}
	// 分类选择器
	const showCategoryPicker = ref(false)
	const categoryColumns = ref([
		[]
	]) // 初始化为空数组
	const categoryMap = ref({}) // 用于存储分类映射关系
	// 加载分类数据
	const loadCategories = async () => {
		try {
			const res = await getClassification(9) // 传参数9获取分类
			if (res.code === 200) {
				// 转换接口数据为选择器需要的格式
				const categories = res.data.map(item => item.label)
				categoryColumns.value = [categories]

				// 构建分类映射关系
				const map = {}
				res.data.forEach(item => {
					map[item.label] = item.value
				})
				categoryMap.value = map
			}
		} catch (error) {
			console.error('加载分类失败:', error)
			uni.showToast({
				title: '加载分类失败',
				icon: 'none'
			})
		}
	}
	// 页面加载时获取分类
	onMounted(() => {
		loadCategories()
	})
	// 文本域样式
	const textareaStyle = {
		height: '200rpx',
		backgroundColor: '#f7f7f7',
		padding: '20rpx',
		borderRadius: '12rpx'
	}
	// 处理分类选择
	const handleCategoryConfirm = (e) => {
		formData.value.category = e.value[0]
		showCategoryPicker.value = false
	}

	// 处理文件上传（保持你原有的逻辑，只增加数量限制）
	const handleUpload = async (event) => {
		try {
			// 检查是否超过最大数量
			const newFiles = Array.isArray(event.file) ? event.file : [event.file]
			if (fileList.value.length + newFiles.length > MAX_FILE_COUNT) {
				return uni.showToast({
					title: `最多只能上传${MAX_FILE_COUNT}张图片`,
					icon: 'none'
				})
			}

			uni.showLoading({
				title: '上传中...',
				mask: true
			})

			const uploadTasks = newFiles.map(file => {
				return uploadImage(file) // 保持你原有的上传方法
			})

			const results = await Promise.all(uploadTasks)

			results.forEach(res => {
				if (res.code === 200) {
					fileList.value.push({
						url: res.data.url,
						name: res.data.origin_name || '未命名文件',
						status: 'success'
					})
				}
			})
		} catch (error) {
			console.error('上传错误:', error)
			uni.showToast({
				title: error.message || '上传失败，请重试',
				icon: 'none'
			})
		} finally {
			uni.hideLoading()
		}
	}
	// 删除文件
	const handleDelete = (index) => {
		fileList.value.splice(index, 1)
	}

	// 提交表单
	const handleSubmit = async () => {
		try {
			// 基础验证
			if (!formData.value.content && fileList.value.length === 0) {
				return uni.showToast({
					title: '请填写内容或上传图片',
					icon: 'none'
				})
			}

			// 手机号验证
			if (formData.value.phone && !validatePhone(formData.value.phone)) {
				return
			}

			uni.showLoading({
				title: '提交中...',
				mask: true
			})

			// 准备数据
			const submitData = {
				feedback_classify: formData.value.category ?
					categoryMap.value[formData.value.category] :
					null, // 使用接口返回的value值
				user_name: formData.value.name || '匿名用户',
				contact_number: formData.value.phone || '',
				feedback_content: formData.value.content || '',
				files: fileList.value.map(file => file.url)
			}

			// 提交数据
			const res = await mySaveFeedback(submitData)

			if (res.code !== 200) {
				throw new Error(res.message || '提交失败')
			}

			uni.showToast({
				title: '提交成功',
				icon: 'success'
			})

			// 重置表单
			formData.value = {
				category: '',
				name: '',
				phone: '',
				content: ''
			}
			fileList.value = []

		} catch (error) {
			console.error('提交错误:', error)
			uni.showToast({
				title: error.message || '提交失败',
				icon: 'none'
			})
		} finally {
			uni.hideLoading()
		}
	}
	// 返回
	const handleBack = () => {
		uni.navigateBack()
	}
</script>

<style lang="scss" scoped>
	.message-box {
		width: 100%;
		min-height: 100vh;
		background-color: #f7f7f7;

		.content {
			padding: 30rpx;
			padding-top: calc(var(--status-bar-height) + 70rpx);

			.form-container {
				display: flex;
				flex-direction: column;
				gap: 40rpx;

				.foembox {
					background: #FFFFFF;
					border-radius: 20rpx;
					padding: 40rpx 30rpx;
					box-shadow: 0 4rpx 12rpx rgba(0, 0, 0, 0.05);
				}

			}

			.form-section {
				background: #FFFFFF;
				border-radius: 20rpx;
				padding: 40rpx 30rpx;
				box-shadow: 0 4rpx 12rpx rgba(0, 0, 0, 0.05);

				.section-title {
					margin-bottom: 30rpx;
					font-size: 28rpx;
					color: #333;
					font-weight: 500;
				}
			}

			/* 调整计数器样式 */
			:deep(.u-textarea__count) {
				background: transparent !important;
				color: #999 !important;
			}

			/* 提交按钮样式 */
			.submit-btn {
				width: 100%;
				height: 88rpx;
				background: #2979FF;
				border-radius: 44rpx;
				color: #fff;
				font-size: 32rpx;
				display: flex;
				align-items: center;
				justify-content: center;
				margin-top: 40rpx;
			}
		}
	}
</style>